package org.example.forum.services.impl;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.example.forum.common.AppResult;
import org.example.forum.common.ResultCode;
import org.example.forum.dao.ArticleMapper;
import org.example.forum.exception.ApplicationException;
import org.example.forum.model.Article;
import org.example.forum.model.Board;
import org.example.forum.model.User;
import org.example.forum.services.IArticleService;
import org.example.forum.services.IBoardService;
import org.example.forum.services.IUserService;
import org.example.forum.utils.StringUtil;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ArticleServiceImpl implements IArticleService {
    @Resource
    private ArticleMapper articleMapper;

    //用户和板块的操作
    @Resource
    private IUserService userService;
    @Resource
    private IBoardService boardService;

    @Override
    public void create(Article article) {
        //非空校验
        if (article == null
                || article.getUserId() == null
                || article.getBoardId() == null
                || StringUtil.isEmpty(article.getTitle())
                || StringUtil.isEmpty(article.getContent())) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //设置默认值
        article.setVisitCount(0);   //访问数量
        article.setReplyCount(0);   //回复数量
        article.setLikeCount(0);    //点赞数量
        article.setDeleteState((byte) 0);
        article.setState((byte) 0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);
        //写入数据库
        int row = articleMapper.insertSelective(article);
        if (row != 1) {
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        //————————————获取用户信息————————————
        User user = userService.selectById(article.getUserId());
        if (user == null) {
            log.warn(ResultCode.FAILED_CREATE.toString()+"，发帖失败，userId = " + article.getUserId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //更新用户发帖数
        userService.addOneArticleCountById(user.getId());

        //————————————获取板块信息————————————
        Board board = boardService.selectById(article.getBoardId());
        //判断有没有找到这个板块
        if (board == null) {
            log.warn(ResultCode.FAILED_CREATE.toString()+"，发帖失败，boardId = " + article.getBoardId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //更新板块中的帖子数量
        boardService.addOneArticleCountById(board.getId());

        //三条sql语句都执行成功，则成功
        log.info(ResultCode.SUCCESS.toString()+"发帖成功");
    }

    @Override
    public List<Article> selectAll() {
        //调用DAO
        List<Article> articles = articleMapper.selectAll();
        //返回结果
        return articles;
    }

    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        //非空校验
        if (boardId == null || boardId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验板块是否存在
        Board board = boardService.selectById(boardId);
        if (board == null) {
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString()+",boardId = "+boardId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        //查询所有 调用DAO
        List<Article> articles = articleMapper.selectAllByBoardId(boardId);
        //返回结果
        return articles;
    }

    @Override
    public Article selectDetailById(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用DAO，获得文章详情
        Article article = articleMapper.selectDetailById(id);
        //校验查询结果
        if (article == null) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //更新操作 更新帖子访问次数
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setVisitCount(article.getVisitCount()+1);
        //保存到数据库中
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //返回帖子详情（为返回的对象进行数据更新
        article.setVisitCount(article.getVisitCount()+1);
        return article;
    }

    @Override
    public Article selectById(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        return article;
    }


    //修改帖子内容
    @Override
    public void modify(Long id, String title, String content) {
        //非空校验
        if (id == null || id <= 0
                || StringUtil.isEmpty(title)
                || StringUtil.isEmpty(content)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //构建要更新的帖子对象 设置要更新的值
        Article updateArticle = new Article();
        updateArticle.setId(id);    //id
        updateArticle.setTitle(title);  //标题
        updateArticle.setContent(content);  //文章正文
        updateArticle.setUpdateTime(new Date());    //更新时间
        //调用DAO实现更新方法
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //如果row正常就说明修改方法没问题了
    }

    @Override
    public void thumbsUpById(Long id) {
        //非空校验
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //获取帖子详情
        Article article = articleMapper.selectByPrimaryKey(id);
        //帖子不存在
        if (article == null || article.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //帖子状态异常
        if ( article.getState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }

        //校验完成后 拿到以前的点赞数加一
        //构造要更新的对象
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setLikeCount(article.getLikeCount()+1);
        updateArticle.setUpdateTime(new Date());
        //调用DAO
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void deleteById(Long id) {
        //非空校验
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //根据id查询帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null || article.getDeleteState() == 1) {
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //创建一个更新对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState((byte) 1);
        //调用DAO执行更新操作
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //更新板块中的帖子数量和发帖数量
        boardService.subOneArticleCountById(article.getBoardId());
        //更新用户发帖数
        userService.subOneArticleCountById(article.getUserId());
        //打印日志
        log.info("删除帖子成功，article id = "+article.getId()+",user id = "+article.getUserId()+",board id = "+article.getBoardId());
    }

    @Override
    public void addOneReplyCountById(Long id) {
        //非空校验
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //根据id查询帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);
        //校验帖子状态
        if (article == null || article.getDeleteState() == 1) {
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //帖子封贴也是状态异常
        if (article.getState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }

        //构造更新对象
        Article updateArticle = new Article();
        updateArticle.setId(id);
        //回复数量在原基础上 +1
        updateArticle.setReplyCount(article.getReplyCount()+1);
        updateArticle.setUpdateTime(new Date());

        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        if (userId == null || userId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userService.selectById(userId);
        //校验用户是否存在
        if (user == null) {
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString()+",userId = "+userId);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //调用DAO
        List<Article> articles = articleMapper.selectByUserId(userId);
        return articles;
    }
}
